package com.pro.controller;


import com.pro.common.SecurityPasswordEncoder;
import com.pro.pojo.*;
import com.pro.service.JsPeopleListService;
import com.pro.service.JsUserService;
import com.pro.utils.IPAndAddressUtil;
import com.pro.utils.MD5Util;
import com.pro.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * ClassName:getJsUserController
 * Package:com.pro.controller
 * Description: 登录Controller层
 *
 * @Date:2021/11/3 上午 11:46
 * @Author:太宰
 */
@Controller
@RequestMapping("/login")
public class JsUserController {
    private String acc;
    private String pass;
    private String acc2;
    private String pass2;
    private String email;
    private Integer UserId;
    private String name;
    @Autowired
    private JsUserService jsUserService;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JsPeopleListService peopleListService;

    @Autowired
    private RedisCache redisCache;

    /*去首页*/
    @RequestMapping("/main")
    public String goMain(HttpServletRequest request,HttpSession session) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        JsUser user = jsUserService.getJsUser(username, userDetails.getPassword());
        if (session.getAttribute("jsUser") == null){
            addJsLoginRecord(user);
        }
        if (user!=null){
            redisCache.setCacheObject("user",user);
            session.setAttribute("jsUser",user);
            acc=user.getAccount();
            pass=user.getPassword();
            email=user.getEmail();
            UserId=user.getUserId();
            name=user.getTrueName();
            if(user.getStatus()==4&&user.getEnabled()==2){
                Date date = new Date();
                SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                String endDate = spf.format(date);
                List<Integer> integers = jsUserService.selectUserEndDate(user.getUserId(), endDate);
                for (Integer in : integers){
                    if(in.equals(1)){
                        session.setAttribute("statuss","您的账户已被封停");
                        return "login";
                    }else{
                        Boolean aBoolean = peopleListService.updateUserStatus(user.getUserId(), 1, 1);
                    }
                }
            }
        }
        return "index";
    }
    /*验证码是否正确*/
    @RequestMapping("/isVerify")
    @ResponseBody
    public JsonData isVerify(HttpServletRequest request,String code){
        String verifyCode = (String) request.getSession().getAttribute("VerifyCode");
        if (code==null){
            return code!=null?JsonData.buildSuccess(false):JsonData.buildError("服务端错误");
        }else if (verifyCode.equals(code.toUpperCase())){
            return code!=null?JsonData.buildSuccess(true):JsonData.buildError("服务端错误");
        }else {
            return code!=null?JsonData.buildSuccess(false):JsonData.buildError("服务端错误");
        }
    }
    /*返回登陆*/
    @RequestMapping("/exit")
    public String exit(HttpSession session) {
        session.removeAttribute("jsUser");
        redisCache.deleteObject("user");
        return "login";
    }

    //添加登录日志
    private JsonData addJsLoginRecord(JsUser user){
        Map<String, Object> ipAndAddressUtil = IPAndAddressUtil.getIPAndAddressUtil();
        JsLoginRecord jsLoginRecord = new JsLoginRecord();
        jsLoginRecord.setUserId(user.getUserId());
        jsLoginRecord.setLoginState(2);
        jsLoginRecord.setLoginType(2);
        jsLoginRecord.setLoginIp(ipAndAddressUtil.get("ip").toString());
        String address = ipAndAddressUtil.get("addr").toString();
        jsLoginRecord.setLoginAddress(address.substring(0,address.length()-3));
        jsLoginRecord.setLoginDate(new Date());
        Boolean aBoolean = jsUserService.addJsLoginRecord(jsLoginRecord);
        return aBoolean!=null?JsonData.buildSuccess(aBoolean):JsonData.buildError("服务端错误");
    }

    /*获取用户登录信息*/
    @RequestMapping("/getUser")
    @ResponseBody
    public JsonData getUser() {
        JsUser use = new JsUser();
        use.setAccount(acc);
        use.setPassword(pass);
        use.setEmail(email);
        use.setTrueName(name);
        use.setUserId(UserId);
        return use!=null?JsonData.buildSuccess(use):JsonData.buildError("服务端错误");
    }

    @RequestMapping("/updateUser")
    @ResponseBody
    public JsonData updateUser(Integer userId,String acatarUrl,String password) {
        password = MD5Util.md5(password);
        Boolean flag = jsUserService.updateUser(userId,acatarUrl,password);
        return flag!=false?JsonData.buildSuccess(flag):JsonData.buildError("服务端错误");
    }


    @RequestMapping("/getLoginMsg")
    @ResponseBody
    public JsonData getLoginMsg() {
        List<JsUser> userList = jsUserService.getLoginMsg(acc);
        JsUser user = userList.get(userList.size() - 1);
        JsUser user1 = null;
        if (userList.size()>=2){
            user1 = userList.get(userList.size() - 2);
        }else {
            user1 = user;
        }
        List<JsUser> jsUsers = new ArrayList<>();
        jsUsers.add(user);
        jsUsers.add(user1);
        return jsUsers!=null?JsonData.buildSuccess(jsUsers):JsonData.buildError("服务端错误");
    }

    @RequestMapping("/count")
    @ResponseBody
    public JsonData count(){
        int count = jsUserService.count();
        return count>=0?JsonData.buildSuccess(count):JsonData.buildError("服务端错误");
    }

    @RequestMapping("/countMonth")
    @ResponseBody
    public JsonData countMonth(){
        List<JsMonthCount> list = jsUserService.countMonth();
        return list!=null?JsonData.buildSuccess(list):JsonData.buildError("服务端错误");
    }
}